package org.common.mongo;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * Mongo上下文
 */
@Slf4j
public class MongoContext {

    private MongoTemplate mongoTemplate;

    public void initMongoContext(String mongoUrl, String user, String password, String dbName) {
        String url = String.format(mongoUrl, user, password, dbName);
        log.info(url);
        MongoClientSettings.Builder settings = MongoClientSettings.builder();
        settings.applyConnectionString(new ConnectionString(url));
        MongoClient mongoClient = MongoClients.create(settings.build());
        mongoTemplate = new MongoTemplate(mongoClient, dbName);
    }

    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

}
